package com.vench.teddy.rabbitmq.consumer;

import com.rabbitmq.client.Channel;
import com.vench.teddy.rabbitmq.constants.MQConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author:vench
 * @Date:2024-09-13 23:25
 */
@Component
@Slf4j
public class DirectListener {

    @RabbitListener(queues = MQConstants.DIRECT_QUEUE_NAME_1)
    public void handler1(String msg, Channel channel, Message message){
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), Boolean.FALSE);
            log.info(MQConstants.DIRECT_QUEUE_NAME_1 + " has received message is {}", msg);
        } catch (IOException e) {
            log.error("message consume failed");
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), Boolean.FALSE, Boolean.TRUE);
            } catch (IOException ex) {
                log.error("message Nack failed");
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }
    }

    @RabbitListener(queues = MQConstants.DIRECT_QUEUE_NAME_2)
    public void handler2(String msg, Channel channel, Message message){
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), Boolean.FALSE);
            log.info(MQConstants.DIRECT_QUEUE_NAME_2 + " has received message is {}", msg);
        } catch (IOException e) {
            log.error("message consume failed");
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), Boolean.FALSE, Boolean.TRUE);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }
    }

}
